package luanvan.app.foodnote;

import org.json.JSONException;
import org.json.JSONObject;

import luanvan.app.foodnote.library.ConnectionDetector;
import luanvan.app.foodnote.library.DatabaseHandler;
import luanvan.app.foodnote.library.UserFunctions;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity {

	Button btnLogin;
	Button btnLinkToRegister;
	EditText inputEmail;
	EditText inputPassword;
	TextView loginErrorMsg;
	
	// JSON Response node names
    private static String KEY_SUCCESS = "success";
    private static String KEY_UID = "uid";
    private static String KEY_NAME = "name";
    private static String KEY_EMAIL = "email";
    
    // flag for Internet connection status
    Boolean isInternetPresent = false;
 
    // Connection detector class
    ConnectionDetector cd;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	requestWindowFeature(Window.FEATURE_LEFT_ICON);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.login);
        
        inputEmail = (EditText) findViewById(R.id.loginEmail);
        inputPassword = (EditText) findViewById(R.id.loginPassword);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
        loginErrorMsg = (TextView) findViewById(R.id.login_error);
        
        cd = new ConnectionDetector(getApplicationContext());
        isInternetPresent = cd.isConnectingToInternet();
        
        btnLogin.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String email = inputEmail.getText().toString();
				String password = inputPassword.getText().toString();
				UserFunctions userFunction = new UserFunctions();
				if(isInternetPresent){
					if(!email.isEmpty() && !password.isEmpty()){
						JSONObject json = userFunction.loginUser(email, password);
						
						// check for login reponse
						try {
							if(json.getString(KEY_SUCCESS) != null){
								loginErrorMsg.setText("");
								String res = json.getString(KEY_SUCCESS);
								if(Integer.parseInt(res) == 1){
									// user successfully logged in
		                            // Store user details in SQLite Database
									
									DatabaseHandler db = new DatabaseHandler(getApplicationContext());
									/*SQLiteDatabase database = db.getWritableDatabase();
									db.onUpgrade(database, 1, 2);*/
									JSONObject json_user = json.getJSONObject("user");
									
									// Clear all previous data in database
									userFunction.logoutUser(getApplicationContext());
									db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID));
									
									Intent dashboard = new Intent(getApplicationContext(), MainActivity.class);
									startActivity(dashboard);
									
									// Close Login Screen
									finish();
								} else {
									loginErrorMsg.setText("Email hoặc mật khẩu không đúng");
								}
							}
						} catch (JSONException e) {
		                    e.printStackTrace();
		                }
					} else {}
				} else {
					showAlertDialog();
				}
			}
		});
        
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
				startActivity(i);
				finish();
			}
		});
    }
    

	public void showAlertDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(LoginActivity.this);
 
        // Setting Dialog Title
        dialog.setTitle("Kết nối Internet");
 
        // Setting Dialog Message
        dialog.setMessage("Thiết bị chưa kết nối internet, vui lòng bật kết nối internet!");
 
        // Setting alert dialog icon
        dialog.setIcon(R.drawable.intetnet);
 
        AlertDialog alert = dialog.create();
        alert.show();
    }
}
